package com.cdream.basic.algorithm.leetcode.tree;

import java.util.PriorityQueue;

/**
 * @author cdream
 * @date 2021/12/24
 */
public class Question1705 {
    public int eatenApples(int[] apples, int[] days) {
        PriorityQueue<int[]> pq = new PriorityQueue<int[]>((a, b) -> a[0] - b[0]);
        int res = 0;
        // 苹果还在成长
        for (int i = 0; i < apples.length; i++) {
            pq.add(new int[]{i + days[i], apples[i]});
            while (!pq.isEmpty()) {
                int[] p = pq.peek();
                if (i >= p[0] || p[1] == 0) {
                    pq.poll();
                } else {
                    p[1]--;
                    res++;
                    break;
                }
            }
        }
        int day = apples.length;
        while (!pq.isEmpty()) {
            int[] p = pq.peek();
            if (day >= p[0] || p[1] == 0) {
                pq.poll();
            } else {
                p[1]--;
                res++;
                day++;
            }
        }
        return res;

    }
}
